package 线程间的通信;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

class WriteData {
    public void writeMethod(OutputStream output) {
	try {
	    System.out.println("write: ");
	    for (int i = 0; i < 300; i++) {
		String outData = "" + (i + 1);
		output.write(outData.getBytes());
		System.out.print(outData);
	    }
	    System.out.println();
	    output.close();

	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	}
    }
}

class ReadData {
    public void readMethod(InputStream input) {
	try {
	    System.out.println("read: ");
	    byte[] byteArray = new byte[20];
	    int readLength = input.read(byteArray);
	    while (readLength != -1) {
		String data = new String(byteArray, 0, readLength);
		System.out.print(data);
		readLength = input.read(byteArray);
	    }
	    System.out.println();
	    input.close();

	} catch (Exception e) {
	    // TODO: handle exception
	    e.printStackTrace();
	}
    }
}

class ThreadWrite extends Thread {
    private PipedOutputStream out;
    private WriteData write;

    public ThreadWrite(PipedOutputStream out, WriteData write) {
	super();
	this.out = out;
	this.write = write;
    }

    public void run() {
	write.writeMethod(out);
    }

}

class ThreadRead extends Thread {
    private PipedInputStream in;
    private ReadData read;

    public ThreadRead(PipedInputStream in, ReadData read) {
	super();
	this.in = in;
	this.read = read;
    }

    public void run() {
	read.readMethod(in);
    }
}

public class Test3_38 {

    private static ThreadRead threadRead;
    private static ThreadWrite threadWrite;

    public static void main(String[] args) {
	// TODO Auto-generated method stub
	WriteData writeData = new WriteData();
	ReadData readData = new ReadData();

	PipedOutputStream pipedOutputStream = new PipedOutputStream();
	PipedInputStream pipedInputStream = new PipedInputStream();

	try {
	    pipedOutputStream.connect(pipedInputStream); // pipedInputStream.connect(pipedOutputStream);
	   

	    threadWrite = new ThreadWrite(pipedOutputStream, writeData);
	    threadRead = new ThreadRead(pipedInputStream, readData);
	    
	    threadRead.start();

	    Thread.sleep(2000);

	    threadWrite.start();
	} catch (Exception e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

    }

}
